﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.ObjectModel;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.Build.Client;
using System.Collections.Specialized;

namespace ShahyadS.TFSBuildInspectionModel
{
	public class BuildAgentCollection : SafeObservableCollection<BuildAgentRow>
	{
		public IBuildServer BuildServer { get; private set; }
		public TfsTeamProjectCollection TeamProjectCollection { get; private set; }
		public IQueuedBuildQueryResult AllBuildInQueue;
		public IBuildAgentQueryResult Agents { get; private set; }
		private Uri _TeamProjectCollectionUrl;
		public Uri TeamProjectCollectionUrl
		{
			get
			{
				return _TeamProjectCollectionUrl;
			}
			set
			{
				_TeamProjectCollectionUrl = value;
				TeamProjectCollection = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(_TeamProjectCollectionUrl);
				BuildServer = (IBuildServer)TeamProjectCollection.GetService(typeof(IBuildServer));
				if (BuildServer.BuildServerVersion == BuildServerVersion.V3)
				{
					var controllers = BuildServer.QueryBuildControllers();
					var rows = (from c in controllers from a in c.Agents.Select(a => new BuildAgentRow(a, this)) select a);
					Items.Clear();
					foreach (var r in rows)
					{
						Items.Add(r);
					}
				}
				else
				{
					Items.Clear();
				}
				OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
			}
		}
		public void updateAllBuildInQueue()
		{
			if (Items.Count > 0)
			{
				var QBuildSpec = BuildServer.CreateBuildQueueSpec("*");
				AllBuildInQueue = BuildServer.QueryQueuedBuilds(QBuildSpec);
				Agents = BuildServer.QueryBuildAgents(BuildServer.CreateBuildAgentSpec());
				Items.ToList().ForEach(r => r.Refresh());
			}
		}
		public BuildAgentCollection()
		{
		}
		public BuildAgentCollection(string teamProjectCollectionUrl)
		{
			TeamProjectCollectionUrl = new Uri(teamProjectCollectionUrl);
		}
		
		public List<string> Refresh()
		{
			var result = new List<string>();
			var before = (from i in Items select i.BuildUri).ToArray();
			Items.ToList().ForEach(r => r.Refresh());
			var after = (from i in Items select i.BuildUri).ToArray();
			var refreshrequitred = (from b in before where !after.Contains(b) select b).Concat(from a in after where !before.Contains(a) select a).ToList();
			foreach (var b in refreshrequitred)
			{
				result.Add(BuildServer.GetBuild(b).BuildDefinition.Name);
			}
			return result;
		}
	}
}
